package com.hong.spring.datasource.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Auther: csh
 * @Date: 2020/8/13 18:12
 * @Description:配置cp30
 */
@Configuration
@PropertySource("c3p0.properties")
public class C3p0Config {

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.user}")
    private String user;

    @Value("${jdbc.password}")
    private String password;

    //添加@Primary防止跟xml里面注册的连接池冲突
    @Primary
    @Bean
    public DataSource init() throws PropertyVetoException, SQLException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setPassword(password);
        dataSource.setUser(user);
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        return dataSource;
    }
}
